<template>
  <div class="unified-interface-editor">
    <!-- 头部信息栏 -->
    <div class="editor-header">
      <div class="interface-info">
        <span class="interface-name" @click="showNameEditDialog">
          {{ interfaceData?.name || '未命名接口' }}
          <el-icon class="edit-icon"><Edit /></el-icon>
        </span>
        <span class="interface-description" v-if="interfaceData?.description">
          {{ interfaceData.description }}
        </span>
      </div>
      <div class="action-buttons">
        <div class="environment-selector">
          <span class="env-label">环境:</span>
          <el-select v-model="testConfig.environment_id" placeholder="选择环境" size="small" style="width: 120px;">
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </div>

        <el-button type="primary" size="default" @click="showImportDialog" plain>
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button v-if="isCreating" type="success" size="default" @click="createInterface" :loading="saving">
          Save
        </el-button>
        <el-button v-if="!isCreating" type="success" size="default" @click="saveInterface" :loading="saving">
          Save
        </el-button>
      </div>
    </div>

    <div class="editor-content">
      <!-- 请求配置区域 -->
      <div class="request-config config-panel" :style="{ height: requestPanelHeight + 'px' }" @wheel="handleRequestConfigWheel">
        <!-- 请求行 -->
        <div class="request-line">
          <el-select v-model="formData.method" :class="methodClass">
            <el-option label="GET" value="GET" class="method-option-get" />
            <el-option label="POST" value="POST" class="method-option-post" />
            <el-option label="PUT" value="PUT" class="method-option-put" />
            <el-option label="DELETE" value="DELETE" class="method-option-delete" />
            <el-option label="PATCH" value="PATCH" class="method-option-patch" />
          </el-select>
          <el-input 
            v-model="formData.url" 
            class="url-input" 
            placeholder="https://api-test.jinweihaowu.com/first-choice/public/supplier/applyRecord/batchAddApplyRecord"
          />
          <el-button type="primary" size="default" @click="executeTest" :loading="testing" class="send-button">
            Send
          </el-button>
        </div>

        <!-- 参数配置标签页 -->
        <div class="params-tabs">
          <el-tabs v-model="activeParamTab" type="card" class="custom-tabs">
                          <!-- Query参数 -->
              <el-tab-pane label="Query" name="query">
                <div class="param-config" @wheel="handleParamConfigWheel">
                  <div class="param-table">
                    <div class="param-table-header">
                      <div class="param-col-key">Key</div>
                      <div class="param-col-value">Value</div>
                      <div class="param-col-description">描述</div>
                      <div class="param-col-actions">操作</div>
                    </div>
                    <div
                      v-for="(param, index) in queryParams"
                      :key="index"
                      class="param-row"
                    >
                      <div class="param-col-key">
                        <el-input 
                          v-model="param.key" 
                          placeholder="Key" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-value">
                        <el-input 
                          v-model="param.value" 
                          placeholder="Value" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-description">
                        <el-input 
                          v-model="param.description" 
                          placeholder="描述" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-actions">
                        <el-button type="danger" size="small" @click="removeQueryParam(index)">
                          删除
                        </el-button>
                      </div>
                    </div>
                    <!-- 始终保持一行空行供编辑 -->
                    <div class="param-row empty-row" @click="addQueryParam">
                      <div class="param-col-key">
                        <el-input 
                          placeholder="Key" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-value">
                        <el-input 
                          placeholder="Value" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-description">
                        <el-input 
                          placeholder="描述" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-actions">
                        <span class="add-hint">点击添加</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <!-- Headers参数 -->
              <el-tab-pane label="Headers" name="headers">
                <div class="param-config" @wheel="handleParamConfigWheel">
                  <div class="param-table">
                    <div class="param-table-header">
                      <div class="param-col-key">Key</div>
                      <div class="param-col-value">Value</div>
                      <div class="param-col-description">描述</div>
                      <div class="param-col-actions">操作</div>
                    </div>
                    <div
                      v-for="(param, index) in headerParams"
                      :key="index"
                      class="param-row"
                    >
                      <div class="param-col-key">
                        <el-input 
                          v-model="param.key" 
                          placeholder="Key" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-value">
                        <el-input 
                          v-model="param.value" 
                          placeholder="Value" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-description">
                        <el-input 
                          v-model="param.description" 
                          placeholder="描述" 
                          size="small"
                        />
                      </div>
                      <div class="param-col-actions">
                        <el-button type="danger" size="small" @click="removeHeaderParam(index)">
                          删除
                        </el-button>
                      </div>
                    </div>
                    <!-- 始终保持一行空行供编辑 -->
                    <div class="param-row empty-row" @click="addHeaderParam">
                      <div class="param-col-key">
                        <el-input 
                          placeholder="Key" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-value">
                        <el-input 
                          placeholder="Value" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-description">
                        <el-input 
                          placeholder="描述" 
                          size="small"
                          readonly
                        />
                      </div>
                      <div class="param-col-actions">
                        <span class="add-hint">点击添加</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <!-- Body参数 -->
              <el-tab-pane label="Body" name="body">
                <div class="param-config" @wheel="handleParamConfigWheel">
                  <div class="param-header">
                    <el-radio-group v-model="bodyType" size="small">
                      <el-radio-button value="json">JSON</el-radio-button>
                      <el-radio-button value="form">Form Data</el-radio-button>
                      <el-radio-button value="raw">Raw</el-radio-button>
                    </el-radio-group>
                    <el-button v-if="bodyType === 'json'" size="small" @click="formatJson">
                      <el-icon><Document /></el-icon>
                      格式化
                    </el-button>
                  </div>

                  <!-- JSON Body -->
                  <div v-if="bodyType === 'json'" class="body-content json-body-container">
                    <CodeHighlight 
                      :code="jsonBody" 
                      language="json" 
                      :show-line-numbers="true"
                      theme="github"
                      @update:code="jsonBody = $event"
                      :editable="true"
                      placeholder="请输入JSON格式的请求体"
                      font-size="12px"
                      style="height: 100%;"
                    />
                    <div v-if="jsonError" class="json-error">
                      {{ jsonError }}
                    </div>
                  </div>

                  <!-- Form Data -->
                  <div v-else-if="bodyType === 'form'" class="body-content">
                    <div class="param-table">
                      <div class="param-table-header">
                        <div class="param-col-key">Key</div>
                        <div class="param-col-value">Value</div>
                        <div class="param-col-description">描述</div>
                        <div class="param-col-actions">操作</div>
                      </div>
                      <div
                        v-for="(field, index) in formFields"
                        :key="index"
                        class="param-row"
                      >
                        <div class="param-col-key">
                          <el-input 
                            v-model="field.key" 
                            placeholder="Key" 
                            size="small"
                          />
                        </div>
                        <div class="param-col-value">
                          <el-input 
                            v-model="field.value" 
                            placeholder="Value" 
                            size="small"
                          />
                        </div>
                        <div class="param-col-description">
                          <el-input 
                            v-model="field.description" 
                            placeholder="描述" 
                            size="small"
                          />
                        </div>
                        <div class="param-col-actions">
                          <el-button type="danger" size="small" @click="removeFormField(index)">
                            删除
                          </el-button>
                        </div>
                      </div>
                      <!-- 始终保持一行空行供编辑 -->
                      <div class="param-row empty-row" @click="addFormField">
                        <div class="param-col-key">
                          <el-input 
                            placeholder="Key" 
                            size="small"
                            readonly
                          />
                        </div>
                        <div class="param-col-value">
                          <el-input 
                            placeholder="Value" 
                            size="small"
                            readonly
                          />
                        </div>
                        <div class="param-col-description">
                          <el-input 
                            placeholder="描述" 
                            size="small"
                            readonly
                          />
                        </div>
                        <div class="param-col-actions">
                          <span class="add-hint">点击添加</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Raw Body -->
                  <div v-else-if="bodyType === 'raw'" class="body-content">
                    <el-input
                      v-model="rawBody"
                      type="textarea"
                      :rows="8"
                      placeholder="请输入原始请求体内容"
                    />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
        </div>


      </div>

      <!-- 拖动分割器 -->
      <div 
        class="resize-handle"
        @mousedown="startResize"
      >
        <div class="resize-line"></div>
      </div>

      <!-- 下部：测试结果 -->
      <div class="result-panel" :style="{ 
        height: responsePanelHeight + 'px',
        '--response-height': responsePanelHeight + 'px'
      }">
        <el-card class="result-card" shadow="never">

          <!-- 空状态 -->
          <div v-if="!testResult" class="empty-result">
            <el-icon class="empty-icon"><Document /></el-icon>
            <p>点击测试按钮开始测试</p>
          </div>

          <!-- 测试中状态 -->
          <div v-else-if="testing" class="testing-status">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在测试...</p>
          </div>

          <!-- Response结果 -->
          <div v-else class="result-content">
            <div class="tabs-header" style="position: relative;">
              <div class="tabs-wrapper">
                <!-- 标签页头部容器，包含标签页和状态码 -->
                <div class="tabs-header-container">
                  <el-tabs type="card" class="result-tabs custom-tabs" v-model="activeResultTab">
                    <el-tab-pane label="Body" name="body">
                      <div class="tab-content">
                        <div class="response-viewer">
                          <CodeHighlight 
                            :code="testResult.error_message || testResult.response_body || ''" 
                            :language="testResult.error_message ? 'plaintext' : 'auto'"
                            :show-line-numbers="true"
                            theme="github"
                            font-size="12px"
                            style="height: 100%;"
                          />
                        </div>
                      </div>
                    </el-tab-pane>
                
                    <el-tab-pane name="cookies">
                      <template #label>
                        <span>Cookies</span>
                      </template>
                      <div class="tab-content">
                        <div class="empty-state">
                          <p>No cookies in this response</p>
                        </div>
                      </div>
                    </el-tab-pane>
                    
                    <el-tab-pane name="headers">
                      <template #label>
                        <span>Headers ({{ Object.keys(testResult.response_headers || {}).length }})</span>
                      </template>
                      <div class="tab-content">
                        <div class="headers-list">
                          <div v-for="[key, value] in Object.entries(testResult.response_headers || {})" :key="key" class="header-row">
                            <span class="header-key">{{ key }}</span>
                            <span class="header-value">{{ value }}</span>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
              
                  <!-- 状态码和响应时间显示在标签页右侧 -->
                  <div 
                    v-if="testResult" 
                    class="tabs-status-inline"
                    :style="{
                      position: 'absolute',
                      top: '6px',
                      right: '16px',
                      zIndex: '100',
                      background: '#f0f2f5',
                      padding: '4px 8px',
                      borderRadius: '4px',
                      boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px'
                    }"
                  >
                    <el-tag 
                      :type="getStatusTagType(testResult.status_code)" 
                      size="small"
                      class="status-tag"
                    >
                      {{ testResult.status_code }}
                    </el-tag>
                    <span class="response-time" style="color: #909399; font-size: 12px; font-weight: 500;">
                      {{ testResult.response_time?.toFixed(2) || 0 }}ms
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 接口名称编辑弹窗 -->
    <el-dialog 
      v-model="nameEditDialogVisible" 
      title="编辑接口信息" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="nameEditForm" label-width="80px">
        <el-form-item label="接口名称" required>
          <el-input 
            v-model="nameEditForm.name" 
            placeholder="请输入接口名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="接口描述">
          <el-input 
            v-model="nameEditForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入接口描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-input 
            v-model="nameEditForm.category" 
            placeholder="请输入接口分类"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="默认环境">
          <el-select 
            v-model="nameEditForm.default_environment_id" 
            placeholder="选择默认测试环境"
            style="width: 100%"
          >
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="nameEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNameEdit" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- CURL导入弹窗 -->
    <el-dialog 
      v-model="importDialogVisible" 
      title="导入CURL命令" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <el-form :model="importForm" label-width="80px">
          <el-form-item label="CURL命令" required>
            <el-input 
              v-model="importForm.curlCommand" 
              type="textarea"
              :rows="8"
              placeholder="请粘贴CURL命令，例如：&#10;curl -X POST 'https://api.example.com/users' \&#10;  -H 'Content-Type: application/json' \&#10;  -H 'Authorization: Bearer token123' \&#10;  -d '{&quot;name&quot;: &quot;John&quot;, &quot;email&quot;: &quot;john@example.com&quot;}'"
              style="font-family: 'Courier New', monospace;"
            />
          </el-form-item>
          <el-form-item>
            <div class="import-tips">
              <el-icon><InfoFilled /></el-icon>
              <span>支持标准CURL格式，将自动解析请求方法、URL、请求头和请求体</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="parseCurlCommand" :loading="importing">解析并导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useToast } from 'vue-toastification'
import { apiAutomationApi } from '@/api/apiAutomation'
import CodeHighlight from '@/components/CodeHighlight.vue'
import { 
  Edit, Check, Close, VideoPlay, Plus, Document, Loading, Upload, InfoFilled
} from '@element-plus/icons-vue'

const props = defineProps({
  interfaceData: {
    type: Object,
    default: null
  },
  environments: {
    type: Array,
    default: () => []
  },
  mode: {
    type: String,
    default: 'view', // view, edit, create
    validator: (value) => ['view', 'edit', 'create'].includes(value)
  }
})

const emit = defineEmits(['interface-saved', 'interface-created', 'cancel'])

const toast = useToast()

// 状态管理
const isCreating = computed(() => props.mode === 'create')
const isEditing = ref(props.mode === 'edit')
const isEditable = computed(() => isCreating.value || isEditing.value)
const saving = ref(false)
const testing = ref(false)
const activeResultTab = ref('body')

// 方法颜色类名
const methodClass = computed(() => {
  return ['method-select', `method-${formData.method.toLowerCase()}`]
})



// 面板高度管理
const requestPanelHeight = ref(400) // 请求面板初始高度
const responsePanelHeight = ref(300) // 响应面板初始高度
const isResizing = ref(false)

// 拖动调整大小
const startResize = (e) => {
  isResizing.value = true
  const startY = e.clientY
  const startRequestHeight = requestPanelHeight.value
  const startResponseHeight = responsePanelHeight.value
  
  const onMouseMove = (e) => {
    if (!isResizing.value) return
    
    const deltaY = e.clientY - startY
    let newRequestHeight = startRequestHeight + deltaY
    let newResponseHeight = startResponseHeight - deltaY
    
    // 设置最小和最大高度限制
    const minHeight = 200
    const maxTotalHeight = 800 // 设置总高度限制
    
    // 确保不超出边界
    if (newRequestHeight < minHeight) {
      newRequestHeight = minHeight
      newResponseHeight = maxTotalHeight - minHeight
    } else if (newResponseHeight < minHeight) {
      newResponseHeight = minHeight
      newRequestHeight = maxTotalHeight - minHeight
    } else if (newRequestHeight + newResponseHeight > maxTotalHeight) {
      // 保持总高度不变
      const ratio = maxTotalHeight / (newRequestHeight + newResponseHeight)
      newRequestHeight = Math.round(newRequestHeight * ratio)
      newResponseHeight = Math.round(newResponseHeight * ratio)
    }
    
    requestPanelHeight.value = newRequestHeight
    responsePanelHeight.value = newResponseHeight
  }
  
  const onMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }
  
  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
}

// 处理请求配置区域的鼠标滚动
const handleRequestConfigWheel = (e) => {
  const requestConfig = e.currentTarget
  
  // 检查当前是否有可滚动的内容
  const canScroll = requestConfig.scrollHeight > requestConfig.clientHeight
  
  if (canScroll) {
    // 如果有滚动条，让默认滚动行为生效
    return
  }
  
  // 如果没有滚动条，将滚动事件传递给整个编辑器内容区域
  e.preventDefault()
  
  // 尝试滚动整个编辑器内容区域
  const editorContent = document.querySelector('.editor-content')
  if (editorContent && editorContent.scrollHeight > editorContent.clientHeight) {
    editorContent.scrollTop += e.deltaY * 0.5 // 减缓滚动速度，提供更好的用户体验
    return
  }
  
  // 如果编辑器内容区域也无法滚动，尝试滚动父级容器
  const parentScrollable = findScrollableParent(requestConfig)
  if (parentScrollable) {
    parentScrollable.scrollTop += e.deltaY * 0.5
  }
}

// 查找可滚动的父级容器
const findScrollableParent = (element) => {
  let parent = element.parentElement
  while (parent) {
    const style = window.getComputedStyle(parent)
    const isScrollable = (style.overflowY === 'auto' || style.overflowY === 'scroll') &&
                        parent.scrollHeight > parent.clientHeight
    if (isScrollable) {
      return parent
    }
    parent = parent.parentElement
  }
  return null
}

// 处理参数配置区域的鼠标滚动
const handleParamConfigWheel = (e) => {
  const paramConfig = e.currentTarget
  
  // 检查当前参数配置区域是否有可滚动的内容
  const canScroll = paramConfig.scrollHeight > paramConfig.clientHeight
  
  if (canScroll) {
    // 如果参数区域本身可以滚动，让默认行为生效
    return
  }
  
  // 如果参数区域无法滚动，将滚动传递给请求配置区域
  e.preventDefault()
  
  // 查找请求配置容器
  const requestConfig = paramConfig.closest('.request-config')
  if (requestConfig && requestConfig.scrollHeight > requestConfig.clientHeight) {
    requestConfig.scrollTop += e.deltaY * 0.5
    return
  }
  
  // 如果请求配置区域也无法滚动，尝试滚动编辑器内容区域
  const editorContent = document.querySelector('.editor-content')
  if (editorContent && editorContent.scrollHeight > editorContent.clientHeight) {
    editorContent.scrollTop += e.deltaY * 0.5
    return
  }
  
  // 最后尝试滚动父级容器
  const parentScrollable = findScrollableParent(paramConfig)
  if (parentScrollable) {
    parentScrollable.scrollTop += e.deltaY * 0.5
  }
}

// 表单数据
const formData = reactive({
  name: '',
  method: 'GET',
  url: '',
  description: '',
  category: ''
})

// 参数数据
const activeParamTab = ref('query')
const queryParams = ref([])
const headerParams = ref([])
const formFields = ref([])

// Body参数
const bodyType = ref('json')
const jsonBody = ref('{}')
const rawBody = ref('')
const jsonError = ref('')

// 测试相关
const testConfig = reactive({
  environment_id: null
})
const testResult = ref(null)

// 名称编辑弹窗
const nameEditDialogVisible = ref(false)
const nameEditForm = reactive({
  name: '',
  description: '',
  category: '',
  default_environment_id: null
})

// CURL导入弹窗
const importDialogVisible = ref(false)
const importing = ref(false)
const importForm = reactive({
  curlCommand: ''
})

// 计算属性
const needsBody = computed(() => {
  return ['POST', 'PUT', 'PATCH'].includes(formData.method)
})

// 初始化表单数据
const initFormData = (data) => {
  if (!data) return
  
  formData.name = data.name || ''
  formData.method = data.method || 'GET'
  formData.url = data.url || ''
  formData.description = data.description || ''
  formData.category = data.category || ''
  
  // 初始化参数数据
  queryParams.value = []
  headerParams.value = []
  formFields.value = []
  
  // 如果有参数数据，转换为编辑器格式
  if (data.parameters) {
    data.parameters.forEach(param => {
      const paramData = {
        key: param.name,
        value: param.default_value || '',
        description: param.description || ''
      }
      
      if (param.param_type === 'query') {
        queryParams.value.push(paramData)
      } else if (param.param_type === 'header') {
        headerParams.value.push(paramData)
      }
    })
  }
  
  // 初始化Body数据
  if (data.body_content) {
    if (data.body_type === 'json') {
      jsonBody.value = data.body_content
    } else if (data.body_type === 'raw') {
      rawBody.value = data.body_content
    }
  }
}

// 更新状态码显示（临时禁用）
// const updateStatusDisplay = () => {
//   nextTick(() => {
//     const navWrap = document.querySelector('.result-tabs .el-tabs__nav-wrap')
//     if (navWrap && testResult.value) {
//       navWrap.setAttribute('data-status', testResult.value.status_code || '')
//       navWrap.setAttribute('data-time', `${testResult.value.response_time?.toFixed(2) || 0}ms`)
//     }
//   })
// }

// 监听接口数据变化
watch(() => props.interfaceData, (newData) => {
  if (newData) {
    initFormData(newData)
    // 清空之前的测试结果
    testResult.value = null
  }
}, { immediate: true })

// 监听测试结果变化，更新状态码显示（临时禁用）
// watch(() => testResult.value, () => {
//   updateStatusDisplay()
// })

// 方法变化处理
const onMethodChange = () => {
  if (!needsBody.value) {
    bodyType.value = 'json'
    jsonBody.value = '{}'
    rawBody.value = ''
    formFields.value = []
  }
}

// 参数管理方法
const addQueryParam = () => {
  queryParams.value.push({
    key: '',
    value: '',
    description: ''
  })
}

const removeQueryParam = (index) => {
  queryParams.value.splice(index, 1)
}

const addHeaderParam = () => {
  headerParams.value.push({
    key: '',
    value: '',
    description: ''
  })
}

const removeHeaderParam = (index) => {
  headerParams.value.splice(index, 1)
}

const addFormField = () => {
  formFields.value.push({
    key: '',
    value: '',
    description: ''
  })
}

const removeFormField = (index) => {
  formFields.value.splice(index, 1)
}

// JSON验证
const validateJson = () => {
  if (!jsonBody.value.trim()) {
    jsonError.value = ''
    return
  }
  
  try {
    JSON.parse(jsonBody.value)
    jsonError.value = ''
  } catch (e) {
    jsonError.value = 'JSON格式不正确: ' + e.message
  }
}

// JSON格式化
const formatJson = () => {
  if (!jsonBody.value.trim()) {
    toast.error('请先输入JSON内容')
    return
  }
  
  try {
    const parsed = JSON.parse(jsonBody.value)
    jsonBody.value = JSON.stringify(parsed, null, 2)
    jsonError.value = ''
    toast.success('JSON格式化完成')
  } catch (e) {
    jsonError.value = 'JSON格式不正确: ' + e.message
    toast.error('JSON格式不正确，无法格式化')
  }
}

// 编辑操作
const startEdit = () => {
  isEditing.value = true
}

const cancelEdit = () => {
  if (isCreating.value) {
    emit('cancel')
  } else {
    isEditing.value = false
    // 重置数据
    if (props.interfaceData) {
      initFormData(props.interfaceData)
    }
  }
}

// 保存接口
const saveInterface = async () => {
  if (!props.interfaceData?.id) {
    toast.error('接口ID不存在')
    return
  }

  try {
    saving.value = true
    
    const updateData = buildInterfaceData()
    const response = await apiAutomationApi.updateInterface(props.interfaceData.id, updateData)
    
    if (response && response.data) {
      toast.success('接口保存成功')
      isEditing.value = false
      emit('interface-saved', response.data)
    }
  } catch (error) {
    console.error('保存接口失败:', error)
    toast.error('保存接口失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    saving.value = false
  }
}

// 创建接口
const createInterface = async () => {
  try {
    saving.value = true
    
    const createData = buildInterfaceData()
    const response = await apiAutomationApi.createInterface(createData)
    
    if (response && response.data) {
      toast.success('接口创建成功')
      emit('interface-created', response.data)
    }
  } catch (error) {
    console.error('创建接口失败:', error)
    toast.error('创建接口失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    saving.value = false
  }
}

// 构建接口数据
const buildInterfaceData = () => {
  const data = {
    name: formData.name,
    method: formData.method,
    url: formData.url,
    description: formData.description,
    category: formData.category,
    body_type: needsBody.value ? bodyType.value : 'none'
  }
  
  // 处理Body内容
  if (needsBody.value) {
    if (bodyType.value === 'json') {
      data.body_content = jsonBody.value
    } else if (bodyType.value === 'raw') {
      data.body_content = rawBody.value
    } else if (bodyType.value === 'form') {
      // Form数据转换为JSON字符串
      const formData = {}
      formFields.value.forEach(field => {
        if (field.key) {
          formData[field.key] = field.value
        }
      })
      data.body_content = JSON.stringify(formData)
    }
  }
  
  // 处理参数
  const parameters = []
  
  // Query参数
  queryParams.value.forEach(param => {
    if (param.key) {
      parameters.push({
        name: param.key,
        param_type: 'query',
        description: param.description,
        default_value: param.value
      })
    }
  })
  
  // Header参数
  headerParams.value.forEach(param => {
    if (param.key) {
      parameters.push({
        name: param.key,
        param_type: 'header',
        description: param.description,
        default_value: param.value
      })
    }
  })
  
  data.parameters = parameters
  
  return data
}

// 执行测试
const executeTest = async () => {
  try {
    testing.value = true
    testResult.value = null

    // 构建测试请求参数
    const parameter_overrides = {}
    
    // 处理Query参数
    queryParams.value.forEach(param => {
      if (param.key && param.value !== undefined) {
        parameter_overrides[`query.${param.key}`] = param.value
      }
    })

    // 处理Header参数
    headerParams.value.forEach(param => {
      if (param.key && param.value !== undefined) {
        parameter_overrides[`header.${param.key}`] = param.value
      }
    })

    // 处理Body参数
    if (needsBody.value) {
      if (bodyType.value === 'json' && jsonBody.value) {
        try {
          JSON.parse(jsonBody.value)
          parameter_overrides['body.json'] = jsonBody.value
        } catch (e) {
          toast.error('JSON格式不正确')
          return
        }
      } else if (bodyType.value === 'form') {
        const formData = {}
        formFields.value.forEach(field => {
          if (field.key && field.value !== undefined) {
            formData[field.key] = field.value
          }
        })
        if (Object.keys(formData).length > 0) {
          parameter_overrides['body.form'] = JSON.stringify(formData)
        }
      } else if (bodyType.value === 'raw' && rawBody.value) {
        parameter_overrides['body.raw'] = rawBody.value
      }
    }

    const testRequest = {
      interface_id: props.interfaceData?.id || 0,
      environment_id: testConfig.environment_id,
      variables: {},
      parameter_overrides
    }

    console.log('发送测试请求:', testRequest)
    const response = await apiAutomationApi.testInterface(testRequest)
    testResult.value = response.data

    if (response.data.success) {
      toast.success('接口测试完成')
    } else {
      toast.error('接口测试失败')
    }
  } catch (error) {
    console.error('接口测试失败:', error)
    toast.error('接口测试失败')
    testResult.value = {
      success: false,
      error_message: error.response?.data?.detail || error.message || '测试失败'
    }
  } finally {
    testing.value = false
  }
}

// 名称编辑相关方法
const showNameEditDialog = () => {
  nameEditForm.name = formData.name
  nameEditForm.description = formData.description
  nameEditForm.category = formData.category || ''
  nameEditForm.default_environment_id = testConfig.environment_id
  nameEditDialogVisible.value = true
}

const saveNameEdit = () => {
  if (!nameEditForm.name.trim()) {
    toast.error('接口名称不能为空')
    return
  }
  
  formData.name = nameEditForm.name
  formData.description = nameEditForm.description
  formData.category = nameEditForm.category
  testConfig.environment_id = nameEditForm.default_environment_id
  
  nameEditDialogVisible.value = false
  toast.success('接口信息已更新')
}

// CURL导入相关方法
const showImportDialog = () => {
  importForm.curlCommand = ''
  importDialogVisible.value = true
}

const parseCurlCommand = async () => {
  if (!importForm.curlCommand.trim()) {
    toast.error('请输入CURL命令')
    return
  }

  importing.value = true

  try {
    const parsed = parseCurl(importForm.curlCommand.trim())
    
    if (!parsed) {
      throw new Error('无法解析CURL命令')
    }

    // 填充解析结果到表单
    formData.method = parsed.method || 'GET'
    formData.url = parsed.url || ''
    
    // 清空现有参数
    queryParams.value = []
    headerParams.value = []
    formFields.value = []
    formData.json_body = ''
    
    // 填充查询参数
    if (parsed.queryParams && parsed.queryParams.length > 0) {
      queryParams.value = parsed.queryParams.map(param => ({
        key: param.key,
        value: param.value,
        description: ''
      }))
    }
    
    // 填充请求头
    if (parsed.headers && parsed.headers.length > 0) {
      headerParams.value = parsed.headers.map(header => ({
        key: header.key,
        value: header.value,
        description: ''
      }))
    }
    
    // 填充请求体
    if (parsed.body) {
      if (typeof parsed.body === 'string') {
        try {
          // 尝试格式化JSON
          const jsonObj = JSON.parse(parsed.body)
          formData.json_body = JSON.stringify(jsonObj, null, 2)
        } catch {
          formData.json_body = parsed.body
        }
      } else {
        formData.json_body = JSON.stringify(parsed.body, null, 2)
      }
    }
    
    // 自动设置接口名称（如果没有的话）
    if (!formData.name && parsed.url) {
      const urlParts = parsed.url.split('/')
      const lastPart = urlParts[urlParts.length - 1]
      if (lastPart && lastPart !== '') {
        formData.name = `${parsed.method} ${lastPart}`
      } else {
        formData.name = `${parsed.method} API`
      }
    }
    
    importDialogVisible.value = false
    toast.success('CURL命令解析成功！')
    
  } catch (error) {
    console.error('解析CURL命令失败:', error)
    toast.error(error.message || '解析CURL命令失败，请检查格式是否正确')
  } finally {
    importing.value = false
  }
}

// CURL解析函数
const parseCurl = (curlCommand) => {
  try {
    // 移除换行符和多余的空格
    const cleanCommand = curlCommand
      .replace(/\\\s*\n\s*/g, ' ')  // 处理行连接符
      .replace(/\s+/g, ' ')         // 合并多个空格
      .trim()

    console.log('清理后的CURL命令:', cleanCommand)

    // 基本的CURL命令解析
    const result = {
      method: 'GET',
      url: '',
      headers: [],
      queryParams: [],
      body: null
    }

    // 解析请求方法 - 简化正则表达式
    const methodMatch = cleanCommand.match(/-X\s+(\w+)/) || cleanCommand.match(/--request\s+(\w+)/)
    if (methodMatch) {
      result.method = methodMatch[1].toUpperCase()
      console.log('解析到方法:', result.method)
    }

    // 解析URL - 简化逻辑，查找引号中或空格分隔的URL
    let url = ''
    
    // 尝试匹配单引号中的URL
    let urlMatch = cleanCommand.match(/'(https?:\/\/[^']+)'/)
    if (urlMatch) {
      url = urlMatch[1]
    } else {
      // 尝试匹配双引号中的URL
      urlMatch = cleanCommand.match(/"(https?:\/\/[^"]+)"/)
      if (urlMatch) {
        url = urlMatch[1]
      } else {
        // 尝试匹配没有引号的URL
        urlMatch = cleanCommand.match(/curl\s+[^-]*?(https?:\/\/\S+)/)
        if (urlMatch) {
          url = urlMatch[1]
        }
      }
    }
    
    if (url) {
      console.log('解析到URL:', url)
      // 分离URL和查询参数
      const [baseUrl, queryString] = url.split('?')
      result.url = baseUrl
      
      if (queryString) {
        const params = new URLSearchParams(queryString)
        for (const [key, value] of params) {
          result.queryParams.push({ key, value })
        }
        console.log('解析到查询参数:', result.queryParams)
      }
    }

    // 解析请求头
    const headerMatches = [...cleanCommand.matchAll(/-H\s+'([^']+)'|--header\s+'([^']+)'|-H\s+"([^"]+)"|--header\s+"([^"]+)"/g)]
    for (const match of headerMatches) {
      const headerStr = match[1] || match[2] || match[3] || match[4]
      if (headerStr) {
        const colonIndex = headerStr.indexOf(':')
        if (colonIndex > 0) {
          const key = headerStr.substring(0, colonIndex).trim()
          const value = headerStr.substring(colonIndex + 1).trim()
          result.headers.push({ key, value })
        }
      }
    }
    console.log('解析到请求头:', result.headers)

    // 解析请求体数据
    const dataMatch = cleanCommand.match(/-d\s+'([^']+)'|--data\s+'([^']+)'|-d\s+"([^"]+)"|--data\s+"([^"]+)"/)
    if (dataMatch) {
      result.body = dataMatch[1] || dataMatch[2] || dataMatch[3] || dataMatch[4]
      console.log('解析到请求体:', result.body)
    }

    console.log('最终解析结果:', result)
    return result
  } catch (error) {
    console.error('CURL解析错误:', error)
    throw new Error('CURL命令格式不正确')
  }
}

// 辅助方法
const getStatusTagType = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) {
    return 'success'
  } else if (statusCode >= 300 && statusCode < 400) {
    return 'warning'
  } else if (statusCode >= 400) {
    return 'danger'
  }
  return 'info'
}

const formatHeaders = (headers) => {
  return Object.entries(headers)
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n')
}

const formatResponseBody = (body) => {
  try {
    const parsed = JSON.parse(body)
    return JSON.stringify(parsed, null, 2)
  } catch (error) {
    return body
  }
}

const getResponseSize = (body) => {
  if (!body) return '0 B'
  const bytes = new Blob([body]).size
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
</script>

<style lang="scss" scoped>
.unified-interface-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex: 1; // 继承父容器的flex空间

  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 0;

    .interface-info {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .interface-name {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        
        &:hover {
          color: #409eff;
          
          .edit-icon {
            opacity: 1;
          }
        }

        .edit-icon {
          opacity: 0;
          transition: opacity 0.2s;
          font-size: 14px;
        }
      }

      .interface-description {
        font-size: 12px;
        color: #909399;
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .action-buttons {
      display: flex;
      align-items: center;
      gap: 12px;

      .environment-selector {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-right: 8px;

        .env-label {
          font-size: 14px;
          color: #606266;
          white-space: nowrap;
        }
      }
      

    }
  }

  .editor-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    width: 100%; // 确保有宽度
    height: 100%; // 确保有高度
    
    // 统一的面板边框样式
    .config-panel, .result-panel {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 16px 24px; // 增加左右padding
      background: #ffffff;
      overflow: auto; // 保持原有滚动条设置
      
      &.config-panel {
        border-left: 3px solid #409eff;
      }
      
      &.result-panel {
        border-left: 3px solid #67c23a;
      }
    }
    
    // 拖动分割器样式
    .resize-handle {
      height: 8px;
      cursor: row-resize;
      display: flex;
      align-items: center;
      justify-content: center;
      user-select: none;
      
      &:hover .resize-line {
        background-color: #409eff;
        height: 3px;
      }
      
      .resize-line {
        width: 60px;
        height: 2px;
        background-color: #dcdfe6;
        border-radius: 2px;
        transition: all 0.2s ease;
      }
    }

    .request-config {
      // padding由config-panel提供，这里不需要额外padding
      
      .request-line {
        display: flex;
        gap: 8px;
        margin-bottom: 20px;
        align-items: center;

        .method-select {
          width: 100px;
          flex-shrink: 0;
          
          // HTTP方法颜色样式
          &.method-get :deep(.el-select__placeholder) {
            color: #67C23A !important;
            font-weight: 600;
          }
          
          &.method-post :deep(.el-select__placeholder) {
            color: #409EFF !important;
            font-weight: 600;
          }
          
          &.method-put :deep(.el-select__placeholder) {
            color: #E6A23C !important;
            font-weight: 600;
          }
          
          &.method-delete :deep(.el-select__placeholder) {
            color: #F56C6C !important;
            font-weight: 600;
          }
          
          &.method-patch :deep(.el-select__placeholder) {
            color: #909399 !important;
            font-weight: 600;
          }
        }
        
        // 下拉框选项颜色 - 使用全局样式
        :global(.el-select-dropdown .method-option-get) {
          color: #67C23A !important;
          font-weight: 600;
        }
        
        :global(.el-select-dropdown .method-option-post) {
          color: #409EFF !important;
          font-weight: 600;
        }
        
        :global(.el-select-dropdown .method-option-put) {
          color: #E6A23C !important;
          font-weight: 600;
        }
        
        :global(.el-select-dropdown .method-option-delete) {
          color: #F56C6C !important;
          font-weight: 600;
        }
        
        :global(.el-select-dropdown .method-option-patch) {
          color: #909399 !important;
          font-weight: 600;
        }

        .url-input {
          flex: 1;
        }
        
        .send-button {
          flex-shrink: 0;
        }
      }
    }

    .params-tabs {
      flex: 1;
      min-height: 0;
      
      // 确保el-tabs能正确传递高度
      :deep(.el-tabs) {
        height: 100%;
        display: flex;
        flex-direction: column;
      }
      
      :deep(.el-tabs__content) {
        flex: 1;
        padding: 0;
      }
      
      :deep(.el-tab-pane) {
        height: 100%;
      }
      
      // 去掉el-tabs__header.is-top的左右padding
      :deep(.el-tabs__header.is-top) {
        padding-left: 0 !important;
        padding-right: 0 !important;
      }
      
      // 接口管理专用的标签页按钮样式，覆盖全局custom-tabs样式
      :deep(.el-tabs__item) {
        height: 28px !important; // 接口管理专用高度
        line-height: 20px !important;
        padding: 4px 12px !important; // 稍微增加左右padding
        font-size: 12px !important;
        margin: 0 2px; // 增加间距
        border-radius: 4px;
        font-weight: 500;
        border: none !important;
        background: transparent;
        color: #606266;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 165, 0, 0.1);
          color: #ff8c00;
        }
        
        &.is-active {
          background: #ff8c00 !important;
          color: white !important;
        }
      }

    }
    
    // 自定义标签页样式
    .custom-tabs {
      // 去掉所有el-tabs__header.is-top的左右padding
      :deep(.el-tabs__header.is-top) {
        padding-left: 0 !important;
        padding-right: 0 !important;
      }
      
      :deep(.el-tabs__nav-wrap) {
        background: none;
        border: none;
        padding: 0;
        box-shadow: none;
      }
      
      :deep(.el-tabs__nav) {
        border: none;
      }
      
      // 设置el-tabs__nav.is-top高度与按钮一致，去除留白
      :deep(.el-tabs__nav.is-top) {
        height: 24px !important;
        min-height: 24px !important;
        display: flex;
        align-items: center;
      }
      
      :deep(.el-tabs__item) {
        border: none !important;
        background: transparent;
        color: #606266;
        font-weight: 500;
        padding: 4px 8px !important; // 进一步减小padding
        margin: 0 1px;
        border-radius: 3px;
        font-size: 12px !important; // 进一步减小字体
        height: 24px !important; // 减小高度
        line-height: 16px !important; // 减小行高
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 165, 0, 0.1);
          color: #ff8c00;
        }
        
        &.is-active {
          background: #ff8c00 !important; // 橙色背景
          color: white !important;
        }
      }
      
      :deep(.el-tabs__active-bar) {
        display: none;
      }
      
      :deep(.el-tabs__content) {
        border: none;
        padding-top: 12px; // 减小上边距
      }
      
      // 专门针对响应结果标签页移除边框
      &.result-tabs {
        :deep(.el-tabs__header) {
          border-bottom: none !important;
        }
      }

      
      .config-section {
        margin-bottom: 24px;
        
        h4 {
          margin: 0 0 12px 0;
          color: #303133;
          font-size: 14px;
          font-weight: 600;
        }
      }
        
      .param-config {
          flex: 1;
          display: flex;
          flex-direction: column;
          min-height: 0;
          overflow: hidden; // 避免与子组件产生双滚动条
          
          // 当包含JSON编辑器时，允许自适应高度
          &:has(.json-body-container) {
            height: auto;
            flex: none; // 不强制占满空间
          }
          .param-header {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 4px !important; // 从12px减少到4px，上移
            padding: 0px 0px !important; // 从8px减少到4px

            // 让按钮贴近上边缘
            display: flex;
            align-items: flex-start;
  
            button {
              margin-top: 0 !important;
            }
          }
          
          .param-table {
            .param-table-header {
              display: flex;
              align-items: center;
              padding: 8px 0;
              background-color: #f5f7fa;
              border-radius: 4px;
              margin-bottom: 8px;
              font-weight: 600;
              color: #606266;
              font-size: 12px;
              text-align: center;
              
              > div {
                text-align: center;
              }
            }
            
            .param-row {
              display: flex;
              align-items: center;
              margin-bottom: 8px;
              
              &.empty-row {
                cursor: pointer;
                opacity: 0.6;
                transition: all 0.3s;
                
                &:hover {
                  opacity: 1;
                  background-color: #f0f9ff;
                }
                
                .add-hint {
                  color: #909399;
                  font-size: 12px;
                  text-align: center;
                }
              }
            }
            
            .param-col-key {
              flex: 1;
              margin-right: 8px;
            }
            
            .param-col-value {
              flex: 1;
              margin-right: 8px;
            }
            
            .param-col-description {
              flex: 1.5;
              margin-right: 8px;
            }
            
            .param-col-actions {
              width: 60px;
              text-align: center;
            }
          }
          
          .empty-params {
            text-align: center;
            color: #909399;
            padding: 20px;
            font-size: 14px;
          }
          
          .add-field-btn {
            margin-top: 8px;
          }
        }
        
        .body-content {
          .json-error {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 4px;
          }
          
          &.json-body-container {
            display: flex;
            flex-direction: column;
            min-height: auto; // 完全根据内容自适应
            max-height: 400px; // 最大高度：约20行代码
            
            .code-highlight-container {
              border: 1px solid #e1e8ed;
              border-radius: 6px;
              background: #f8f9fa;
              box-sizing: border-box; // 确保border不会增加额外尺寸
              min-height: auto; // 完全根据内容自适应
            }
          }
        }
        
        .body-type-tabs {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 16px;
          flex-wrap: nowrap; // 防止换行
          
          .el-radio-group {
            flex-shrink: 0;
          }
          
          .el-button {
            flex-shrink: 0;
          }
        }
      }
    }
  }

    .result-panel {
      // 高度由JavaScript动态控制
      // padding由统一面板样式提供
      
      .result-card {
        height: 100%;
        border: none !important;
        
        :deep(.el-card__body) {
          padding: 0 !important;
        }
        .result-header {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .result-title {
            font-weight: 600;
            font-size: 16px;
            color: #303133;
          }

          .result-status {
            display: flex;
            align-items: center;
            gap: 12px;

            .status-tag {
              font-weight: 600;
              border: none;
            }

            .response-time {
              color: #909399;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }

        .empty-result,
        .testing-status {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 200px;
          color: #909399;

          .empty-icon,
          .is-loading {
            font-size: 48px;
            margin-bottom: 12px;
          }
        }

        .result-content {
          height: 100%;
          display: flex;
          flex-direction: column;
          
          .result-section {
            margin-bottom: 20px;

            h4 {
              margin: 0 0 12px 0;
              color: #303133;
              border-bottom: 1px solid #e4e7ed;
              padding-bottom: 8px;
            }

            .code-block {
              background-color: #f5f7fa;
              border: 1px solid #e4e7ed;
              border-radius: 4px;
              padding: 12px;
              max-height: 200px;
              overflow: auto;

              pre {
                margin: 0;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                line-height: 1.4;
                white-space: pre-wrap;
                word-break: break-all;
              }
            }

        .tabs-header {
          margin-top: 16px;
          
          .tabs-wrapper {
            position: relative !important;
          }
        }
        
        .response-status-header {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          padding: 8px 12px;
          background: #f8f9fa;
          border-bottom: 1px solid #e1e8ed;
          
          .status-info {
            display: flex;
            align-items: center;
            gap: 8px;
            
            .status-tag {
              font-weight: 600;
            }
            
            .response-time {
              color: #909399;
              font-size: 12px;
              font-weight: 500;
            }
          }
        }
        
        .tabs-header {
          position: relative;
        }
        
        .tabs-status-inline {
          position: absolute !important;
          top: 8px !important;
          right: 16px !important;
          display: flex !important;
          align-items: center !important;
          gap: 8px !important;
          background: #f0f2f5 !important;
          padding: 4px 8px !important;
          border-radius: 4px !important;
          z-index: 100 !important;
          box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
        }
        
        .tabs-status-inline .status-tag {
          font-weight: 600 !important;
        }
        
        .tabs-status-inline .response-time {
          color: #909399 !important;
          font-size: 12px !important;
          font-weight: 500 !important;
        }

        .result-tabs {
          flex: 1;
          display: flex;
          flex-direction: column;
          min-height: 0;
          
          // 确保el-tabs能正确传递高度
          :deep(.el-tabs) {
            height: 100%;
            display: flex;
            flex-direction: column;
          }
          
          :deep(.el-tabs__content) {
            flex: 1;
            padding: 0;
          }
          
          :deep(.el-tab-pane) {
            height: 100%;
          }


          .tab-content {
            padding: 0;
            flex: 1;
            display: flex;
            flex-direction: column;

            .response-viewer {
              flex: 1;
              .code-highlight-container {
                border: none;
                border-radius: 0;
                background: transparent;
                overflow: auto;
              }
            }

            .json-viewer {
              max-height: 400px;
              overflow: auto;

              .json-content {
                margin: 0;
                padding: 16px;
                background: #fafafa;
                font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                font-size: 12px;
                line-height: 1.5;
                color: #2c3e50;
                white-space: pre-wrap;
                word-break: break-all;
              }
            }

            .headers-list {
              padding: 12px;
              
              .header-row {
                display: flex;
                padding: 8px 16px;
                border-bottom: 1px solid #f0f0f0;

                &:last-child {
                  border-bottom: none;
                }

                .header-key {
                  width: 200px;
                  font-weight: 600;
                  color: #606266;
                  flex-shrink: 0;
                }

                .header-value {
                  flex: 1;
                  color: #303133;
                  word-break: break-all;
                }
              }
            }

            .empty-state {
              padding: 40px;
              text-align: center;
              color: #909399;
            }
          }
        }

        .error-section {
          margin-top: 16px;

          .error-message {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #f56c6c;
            background-color: #fef0f0;
            border: 1px solid #fbc4c4;
            border-radius: 4px;
            padding: 12px;

            .error-icon {
              flex-shrink: 0;
            }
          }
        }
      }
    }
  }
}

// CURL导入对话框样式
.import-content {
  .import-tips {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #909399;
    font-size: 13px;
    
    .el-icon {
      color: #409eff;
    }
  }
}
</style>